package com.fowo.api.tiktok.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fowo.api.datainterface.constants.Constants;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.datainterface.service.impl.DatainterfaceServiceImpl;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.datainterface.util.JsonUtil;
import com.fowo.api.entity.*;
import com.fowo.api.model.nav.sell.order.NavSellOrderVo;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailItemVo;
import com.fowo.api.model.nav.sell.order.face.NavSellOrderFaceItemVo;
import com.fowo.api.model.nav.sell.order.platform.NavSellOrderPlatformItemVo;
import com.fowo.api.model.tmp.tiktok.order.TmpTiktokOrderItemVo;
import com.fowo.api.model.tmp.tiktok.order.TmpTiktokOrderSearchParamPo;
import com.fowo.api.service.impl.*;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.tiktok.util.TiktokUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.util.*;

@Component
@Slf4j
public class TiktokOrderService {

    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private Common common;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private TmpTiktokOrderServiceImpl tmpTiktokOrderService;
    @Resource
    private TmpTiktokOrderItemServiceImpl tmpTiktokOrderItemService;
    @Resource
    private NavSellOrderServiceImpl navSellOrderService;
    @Resource
    private NavSellOrderPlatformServiceImpl navSellOrderPlatformService;
    @Resource
    private SysCountryServiceImpl sysCountryService;
    @Resource
    private FileService fileService;
    @Resource
    private DatainterfaceServiceImpl datainterfaceService;
//    @Resource
//    private TmpTiktokOrderFaceServiceImpl tmpTiktokOrderFaceService;

    public static final String ORDER_URL = "/order/202309/orders/search";

    @Transactional(rollbackFor = Exception.class)
    public void syncOrder() throws Exception {
        tmpTiktokOrderService.remove(null);
        tmpTiktokOrderItemService.remove(null);
        getOrderList();
        log.info("拉取订单数据完成");
        saveNavSellOrder();
        log.info("插入订单数据完成");

    }

    public void getOrderList() throws JsonProcessingException {

        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform, "TikTok")
                .eq(ShopInfo::getSellerAuthStatus, "SQ01"));

        for (ShopInfo shopInfo : list) {
            Map<String,String> header = new HashMap<>();
            header.put("x-tts-access-token", shopInfo.getRefreshToken());

            int page_size = 100;

            Map<String, Object> query = new TreeMap<>();
            query.put("access_token", shopInfo.getRefreshToken());
            query.put("shop_cipher", shopInfo.getMarketplaceId());
            query.put("page_size", page_size);

            Map<String, Object> params = new HashMap<>();
//            String startTime = DateUtil.formatDate(DateUtil.yesterday().getTime()/1000);
            params.put("update_time_ge", DateUtil.yesterday().getTime() / 1000L);

            Map<String,Object> currentParamsMap = new HashMap<>();
            currentParamsMap.put("params",params);
            currentParamsMap.put("query",query);

            Object result = datainterfaceService.executeInterface(null, "EC00529", null, currentParamsMap, header);

            JSONObject body = JSONUtil.parseObj(result);
            if (body.getInt("code") == 0) {
                JSONObject data = body.getJSONObject("data");
                int totalCount = data.getInt("total_count");
                JSONArray orders = data.getJSONArray("orders");
                //保存到临时表
                saveTmpTiktokOrder(orders, shopInfo);
                int page = totalCount / page_size;
                if (totalCount % page_size != 0) {
                    page += 1;
                }
                String nextPageToken = data.getStr("next_page_token");
                for (int i = 1; i < page; i++) {
                    if (StrUtil.isNotBlank(nextPageToken)) { //下一页
                        nextPageToken = getNext(nextPageToken, shopInfo);
                    }
                }
            } else {
                log.error("获取TikTok订单异常，" + body.getStr("message"));
            }
        }
    }
    /**
     * 下一页订单
     *
     * @param nextPageToken
     * @param shopInfo
     */
    public String getNext(String nextPageToken, ShopInfo shopInfo) throws JsonProcessingException {

        Map<String,String> header = new HashMap<>();
        header.put("x-tts-access-token", shopInfo.getRefreshToken());

        int page_size = 100;
        Map<String, Object> query = new TreeMap<>();
        query.put("access_token", shopInfo.getRefreshToken());
        query.put("shop_cipher", shopInfo.getMarketplaceId());
        query.put("page_size", page_size);
        query.put("page_token", nextPageToken);

        Map<String, Object> params = new HashMap<>();
        params.put("update_time_ge", DateUtil.yesterday().getTime() / 1000L);

        Map<String,Object> currentParamsMap = new HashMap<>();
        currentParamsMap.put("params",params);
        currentParamsMap.put("query",query);

        Object result = datainterfaceService.executeInterface(null, "EC00529", null, currentParamsMap, header);

        JSONObject body = JSONUtil.parseObj(result);
        if (body.getInt("code") == 0) {
            JSONObject data = body.getJSONObject("data");
            JSONArray orders = data.getJSONArray("orders");
            //保存到临时表
            saveTmpTiktokOrder(orders, shopInfo);
            return data.getStr("next_page_token");
        } else {
            log.error("获取TikTok订单异常，" + body.getStr("message"));
        }
        return null;
    }

//    public void getOrderList() throws JsonProcessingException {
//        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode, "TikTok"), false);
//        String rootPath = entityAuthority.getRootPath();
//        String appKey = common.getAuthoritySimpleFactory(entityAuthority, "appKey");
//        String appSecret = common.getAuthoritySimpleFactory(entityAuthority, "appSecret");
//
//        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
//                .eq(ShopInfo::getPlatform, "TikTok")
//                .eq(ShopInfo::getSellerAuthStatus, "SQ01"));
//
//        for (ShopInfo shopInfo : list) {
//            HttpHeaders header = new HttpHeaders();
//            header.set("Content-Type", "application/json");
//            header.set("x-tts-access-token", shopInfo.getRefreshToken());
//
//            Long timestamp = System.currentTimeMillis() / 1000;
//            int page_size = 100;
//
//            Map<String, Object> query = new TreeMap<>();
//            query.put("access_token", shopInfo.getRefreshToken());
//            query.put("app_key", appKey);
//            query.put("shop_cipher", shopInfo.getMarketplaceId());
//            query.put("timestamp", timestamp);
//            query.put("page_size", page_size);
//
//            Map<String, Object> params = new HashMap<>();
////            String startTime = DateUtil.formatDate(DateUtil.yesterday().getTime()/1000);
//            params.put("update_time_ge", DateUtil.yesterday().getTime() / 1000L);
//
//            String sign = TiktokUtil.getSign(appSecret, ORDER_URL, query, JSONUtil.toJsonStr(params));
//            query.put("sign", sign);
//
//            StringBuilder pathParam = new StringBuilder();
//            for (String key : query.keySet()) {
//                pathParam.append("&").append(key).append("=").append(query.get(key));
//            }
//            String url = rootPath + ORDER_URL + "?" + pathParam.substring(1);
//            Object result = TiktokUtil.getBaseAspect().httpRequest(url, HttpMethod.POST, params, header, Object.class, Constants.Read, StrUtil.EMPTY);
//
//            JSONObject body = JSONUtil.parseObj(result);
//            if (body.getInt("code") == 0) {
//                JSONObject data = body.getJSONObject("data");
//                int totalCount = data.getInt("total_count");
//                JSONArray orders = data.getJSONArray("orders");
//                //保存到临时表
//                saveTmpTiktokOrder(orders, shopInfo);
//                int page = totalCount / page_size;
//                if (totalCount % page_size != 0) {
//                    page += 1;
//                }
//                String nextPageToken = data.getStr("next_page_token");
//                for (int i = 1; i < page; i++) {
//                    if (StrUtil.isNotBlank(nextPageToken)) { //下一页
//                        nextPageToken = getNext(entityAuthority, nextPageToken, shopInfo);
//                    }
//                }
//            } else {
//                log.error("获取TikTok订单异常，" + body.getStr("message"));
//            }
//        }
//    }

//    /**
//     * 下一页订单
//     *
//     * @param entityAuthority
//     * @param nextPageToken
//     * @param shopInfo
//     */
//    public String getNext(DatainterfaceAuthority entityAuthority, String nextPageToken, ShopInfo shopInfo) throws JsonProcessingException {
//        String rootPath = entityAuthority.getRootPath();
//        String appKey = common.getAuthoritySimpleFactory(entityAuthority, "appKey");
//        String appSecret = common.getAuthoritySimpleFactory(entityAuthority, "appSecret");
//
//        HttpHeaders header = new HttpHeaders();
//        header.set("Content-Type", "application/json");
//        header.set("x-tts-access-token", shopInfo.getRefreshToken());
//
//        Long timestamp = System.currentTimeMillis() / 1000;
//        int page_size = 100;
//        Map<String, Object> query = new TreeMap<>();
//        query.put("access_token", shopInfo.getRefreshToken());
//        query.put("app_key", appKey);
//        query.put("shop_cipher", shopInfo.getMarketplaceId());
//        query.put("timestamp", timestamp);
//        query.put("page_size", page_size);
//        query.put("page_token", nextPageToken);
//
//        Map<String, Object> params = new HashMap<>();
////        String startTime = DateUtil.formatDate(DateUtil.yesterday());
//        params.put("update_time_ge", DateUtil.yesterday().getTime() / 1000L);
//
//        String sign = TiktokUtil.getSign(appSecret, ORDER_URL, query, JSONUtil.toJsonStr(params));
//        query.put("sign", sign);
//
//        StringBuilder pathParam = new StringBuilder();
//        for (String key : query.keySet()) {
//            pathParam.append("&").append(key).append("=").append(query.get(key));
//        }
//        String url = rootPath + ORDER_URL + "?" + pathParam.substring(1);
//        Object result = TiktokUtil.getBaseAspect().httpRequest(url, HttpMethod.POST, params, header, Object.class, Constants.Read, StrUtil.EMPTY);
//
//        JSONObject body = JSONUtil.parseObj(result);
//        if (body.getInt("code") == 0) {
//            JSONObject data = body.getJSONObject("data");
//            JSONArray orders = data.getJSONArray("orders");
//            //保存到临时表
//            saveTmpTiktokOrder(orders, shopInfo);
//            return data.getStr("next_page_token");
//        } else {
//            log.error("获取TikTok订单异常，" + body.getStr("message"));
//        }
//        return null;
//    }

    /**
     * 保存订单数据到临时表
     *
     * @param orders
     * @param shopInfo
     */
    public void saveTmpTiktokOrder(JSONArray orders, ShopInfo shopInfo) throws JsonProcessingException {
        CopyOptions copyOptions = CopyOptions.create();
        copyOptions.setOverride(false);
        copyOptions.setIgnoreNullValue(true);

        List<TmpTiktokOrder> orderList = new ArrayList<>();
        List<TmpTiktokOrderItem> orderItemList = new ArrayList<>();
        for (int i = 0; i < orders.size(); i++) {

            final JSONObject orderObject = orders.getJSONObject(i);
            TmpTiktokOrder tmpTiktokOrder = JsonUtil.getJsonToBeanSafe(orderObject, TmpTiktokOrder.class);

            final JSONArray packages = orderObject.getJSONArray("packages");
            String packageIds = "";
            for (int j = 0; j < packages.size(); j++) {
                String packageId = packages.getJSONObject(j).getStr("id");
                packageIds = packageIds + packageId + ",";
            }
            tmpTiktokOrder.setPackageIds(StrUtil.isBlank(packageIds) ? "" : packageIds.substring(0, packageIds.length() - 1));
            tmpTiktokOrder.setCreateTime(TiktokUtil.secondToDate(orderObject.getLong("create_time")));
            tmpTiktokOrder.setPaidTime(TiktokUtil.secondToDate(orderObject.getLong("paid_time")));
            tmpTiktokOrder.setRtsTime(TiktokUtil.secondToDate(orderObject.getLong("rts_time")));
            tmpTiktokOrder.setRtsSlaTime(TiktokUtil.secondToDate(orderObject.getLong("rts_sla_time")));
            tmpTiktokOrder.setTtsSlaTime(TiktokUtil.secondToDate(orderObject.getLong("tts_sla_time")));
            tmpTiktokOrder.setCancelOrderSlaTime(TiktokUtil.secondToDate(orderObject.getLong("cancel_order_sla_time")));
            tmpTiktokOrder.setLastUpdateTime(TiktokUtil.secondToDate(orderObject.getLong("update_time")));
            tmpTiktokOrder.setDeliverySlaTime(TiktokUtil.secondToDate(orderObject.getLong("delivery_sla_time")));
            tmpTiktokOrder.setRequestCancelTime(TiktokUtil.secondToDate(orderObject.getLong("request_cancel_time")));
            tmpTiktokOrder.setDeliveryOptionRequiredDeliveryTime(TiktokUtil.secondToDate(orderObject.getLong("delivery_option_required_delivery_time")));
            tmpTiktokOrder.setShippingDueTime(TiktokUtil.secondToDate(orderObject.getLong("shipping_due_time")));
            tmpTiktokOrder.setCollectionDueTime(TiktokUtil.secondToDate(orderObject.getLong("collection_due_time")));
            tmpTiktokOrder.setDeliveryDueTime(TiktokUtil.secondToDate(orderObject.getLong("delivery_due_time")));
            tmpTiktokOrder.setCollectionTime(TiktokUtil.secondToDate(orderObject.getLong("collection_time")));
            tmpTiktokOrder.setDeliveryTime(TiktokUtil.secondToDate(orderObject.getLong("delivery_time")));
            tmpTiktokOrder.setCancelTime(TiktokUtil.secondToDate(orderObject.getLong("cancel_time")));

            tmpTiktokOrder.setSid(shopInfo.getId());
            tmpTiktokOrder.setOrderId(orderObject.getStr("id"));

            final JSONObject payment = orderObject.getJSONObject("payment");
            TmpTiktokOrder tmpTiktokOrderPayment = JSONUtil.toBean(payment, TmpTiktokOrder.class);
            BeanUtil.copyProperties(tmpTiktokOrderPayment, tmpTiktokOrder, copyOptions);

            final JSONObject address = orderObject.getJSONObject("recipient_address");
            TmpTiktokOrder tmpTiktokOrderAddress = JSONUtil.toBean(address, TmpTiktokOrder.class);
            final JSONArray districtInfo = address.getJSONArray("district_info");
            for (int j = 0; j < districtInfo.size(); j++) {
                JSONObject district = districtInfo.getJSONObject(j);
                final String address_level_name = district.getStr("address_level_name");
                switch (address_level_name) {
                    case "Country":
                        tmpTiktokOrderAddress.setCountry(district.getStr("address_name"));
                        break;
                    case "State":
                        tmpTiktokOrderAddress.setAddressState(district.getStr("address_name"));
                        break;
                    case "County":
                        tmpTiktokOrderAddress.setAddressCounty(district.getStr("address_name"));
                        break;
                    case "City":
                        tmpTiktokOrderAddress.setAddressCity(district.getStr("address_name"));
                        break;
                    case "District":
                        tmpTiktokOrderAddress.setAddressDistrict(district.getStr("address_name"));
                        break;
                    case "Town":
                        tmpTiktokOrderAddress.setAddressTown(district.getStr("address_name"));
                        break;
                }
            }

            BeanUtil.copyProperties(tmpTiktokOrderAddress, tmpTiktokOrder, copyOptions);
            tmpTiktokOrder.setId(null);
            orderList.add(tmpTiktokOrder);
            final JSONArray items = orderObject.getJSONArray("line_items");
            for (int j = 0; j < items.size(); j++) {
                final JSONObject itemObject = items.getJSONObject(j);
                TmpTiktokOrderItem tmpTiktokOrderItem = JSONUtil.toBean(itemObject, TmpTiktokOrderItem.class);
                tmpTiktokOrderItem.setOrderId(tmpTiktokOrder.getOrderId());
                tmpTiktokOrderItem.setItemId(itemObject.getStr("id"));
                final JSONArray itemTax = itemObject.getJSONArray("item_tax");
                if (null != itemTax) {
                    final JSONObject taxObject = itemTax.getJSONObject(0);
                    tmpTiktokOrderItem.setTaxAmount(taxObject.getBigDecimal("tax_amount"));
                    tmpTiktokOrderItem.setTaxRate(taxObject.getBigDecimal("tax_rate"));
                }
                tmpTiktokOrderItem.setId(null);
                orderItemList.add(tmpTiktokOrderItem);
            }
        }
        tmpTiktokOrderService.saveBatch(orderList);
        tmpTiktokOrderItemService.saveBatch(orderItemList);
    }

    /**
     * 保存至订单管理
     *
     * @throws Exception
     */
    public void saveNavSellOrder() throws Exception {
        TmpTiktokOrderSearchParamPo search = new TmpTiktokOrderSearchParamPo();
        search.setDisableDataPremissions(true);
        final List<TmpTiktokOrderItemVo> orderItemVoList = tmpTiktokOrderService.search(search);
        for (TmpTiktokOrderItemVo order : orderItemVoList) {
            if(order.getStatus().equals("AWAITING_COLLECTION")){//卖方已安排发货，但包裹仍在等待交给承运人
                NavSellOrder oldNavSellOrder = getNavSellOrderByPlatformOrderId(order.getOrderId());
                if (null == oldNavSellOrder) {
                    NavSellOrderVo navSellOrder = buildNavSellOrder(order);
                    navSellOrderService.create(navSellOrder);
                }
            }else if(order.getStatus().equals("CANCELLED")){//取消订单
                NavSellOrder oldNavSellOrder = getNavSellOrderByPlatformOrderId(order.getOrderId());
                if(null != oldNavSellOrder){
                    updateNavSellOrder(oldNavSellOrder);
                }
            }
        }
    }

    /**
     * 冻结订单
     * @param navSellOrder
     */
    public void updateNavSellOrder(NavSellOrder navSellOrder) throws Exception {
        navSellOrder.setStatus("-1");
        navSellOrder.setTag(navSellOrderService.tagHandler(navSellOrder.getTag(),"12,26"));
        navSellOrderService.updateById(navSellOrder);
    }

    /**
     * 根据平台单号获取订单
     *
     * @param platformOrderId
     * @return
     */
    public NavSellOrder getNavSellOrderByPlatformOrderId(String platformOrderId) {
        NavSellOrderPlatform navSellOrderPlatform = navSellOrderPlatformService.getOne(Wrappers.lambdaQuery(NavSellOrderPlatform.class)
                .eq(NavSellOrderPlatform::getPlatformOrderId, platformOrderId)
                .eq(NavSellOrderPlatform::getPlatform, "TikTok"));
        if (null == navSellOrderPlatform) {
            return null;
        }
        NavSellOrder navSellOrder = navSellOrderService.getById(navSellOrderPlatform.getParentNavSellOrder());
        return navSellOrder;
    }

    /**
     * 构建订单管理数据
     *
     * @param tiktokOrder
     * @return
     */
    public NavSellOrderVo buildNavSellOrder(TmpTiktokOrderItemVo tiktokOrder) {
        NavSellOrderVo navSellOrder = new NavSellOrderVo();

        final List<TmpTiktokOrderItem> tiktokOrderGoodsList = tmpTiktokOrderItemService.list(Wrappers.lambdaQuery(TmpTiktokOrderItem.class).eq(TmpTiktokOrderItem::getOrderId, tiktokOrder.getOrderId()));
        final List<SysCountry> countries = sysCountryService.list(Wrappers.lambdaQuery(SysCountry.class).likeRight(SysCountry::getCountryCn, tiktokOrder.getCountry()));
        // 基础信息
        navSellOrder.setShopInfo(tiktokOrder.getSid());
        navSellOrder.setCurrency(tiktokOrder.getCurrency());
        navSellOrder.setType(tiktokOrderGoodsList.size() == 1 ? "1" : "2"); // 1一件一单；2一件多单
        navSellOrder.setStatus("1");
//        navSellOrder.setSite();
        navSellOrder.setSplitType("1");
        navSellOrder.setPaymentWay("1");//tiktokOrder.getPaymentMethodName() 支付方式
        navSellOrder.setBuyerName(tiktokOrder.getName());
        navSellOrder.setDeliveryReceipt(tiktokOrder.getName());
        navSellOrder.setDeliveryZipCode(tiktokOrder.getPostalCode());
        navSellOrder.setDeliveryPhone(tiktokOrder.getPhoneNumber());
        navSellOrder.setDeliveryCountry(CollectionUtil.isEmpty(countries) ? null : countries.get(0).getId());
        navSellOrder.setDeliveryProvince(tiktokOrder.getAddressState());
        navSellOrder.setDeliveryCity(tiktokOrder.getAddressCity());
        navSellOrder.setDeliveryArea(tiktokOrder.getAddressDistrict());
        navSellOrder.setDeliveryAddressType("1");
        String address = tiktokOrder.getAddressDetail();
        if (StrUtil.isNotBlank(tiktokOrder.getAddressLine1())) {
            address = address + " " + tiktokOrder.getAddressLine1();
        }
        navSellOrder.setDeliveryAddress1(address);
        navSellOrder.setDeliveryAddress2(tiktokOrder.getAddressLine2());
        navSellOrder.setDeliveryType("2");
        navSellOrder.setDeliveryCodeOrder(tiktokOrder.getIsCod().toString());
        navSellOrder.setDeliveryTrackId(tiktokOrder.getTrackingNumber());
        navSellOrder.setPackageIds(tiktokOrder.getPackageIds());
        // 平台信息
        NavSellOrderPlatformItemVo navSellOrderPlatform = new NavSellOrderPlatformItemVo();
        navSellOrderPlatform.setPlatformOrderId(tiktokOrder.getOrderId());
        navSellOrderPlatform.setCancelTime(tiktokOrder.getCancelTime());
        navSellOrderPlatform.setLatestShipTime(tiktokOrder.getRtsTime());
        navSellOrderPlatform.setSource("1");
        navSellOrderPlatform.setPaymentStatus(tiktokOrder.getStatus().equals("UNPAID") ? "1" : "0");
        navSellOrderPlatform.setPaymentTime(tiktokOrder.getPaidTime());
        navSellOrderPlatform.setPlatform("TikTok");
        navSellOrderPlatform.setPurchaseTime(tiktokOrder.getCreateTime());
//        navSellOrderPlatform.setShippingStatus("");
        navSellOrderPlatform.setStatus(tiktokOrder.getStatus());
        navSellOrderPlatform.setCountry(CollectionUtil.isEmpty(countries) ? null : countries.get(0).getId());
        List<NavSellOrderPlatformItemVo> platformList = new ArrayList<>();
        platformList.add(navSellOrderPlatform);
        navSellOrder.setPlatform(platformList);

        // 产品信息
        NavSellOrderDetailItemVo navSellOrderDetail;
        List<NavSellOrderDetailItemVo> sellOrderDetailList = new ArrayList<>();
        for (TmpTiktokOrderItem orderGoods : tiktokOrderGoodsList) {

            navSellOrderDetail = new NavSellOrderDetailItemVo();
            navSellOrderDetail.setShopInfo(tiktokOrder.getSid());
            navSellOrderDetail.setPlatformOrderId(orderGoods.getOrderId());
            navSellOrderDetail.setItemFromName("1");

            navSellOrderDetail.setGoodsTitle(orderGoods.getProductName());
            navSellOrderDetail.setGoodsCode(orderGoods.getProductId());
            navSellOrderDetail.setMsku(orderGoods.getSellerSku());
            navSellOrderDetail.setAttribute(orderGoods.getSkuName());
//            navSellOrderDetail.setSalesRevenueAmount();//销售收益
            navSellOrderDetail.setPrice(orderGoods.getSalePrice());
            navSellOrderDetail.setSaleTax(orderGoods.getTaxAmount());
            navSellOrderDetail.setDiscount(orderGoods.getPlatformDiscount().add(orderGoods.getSellerDiscount()));
            navSellOrderDetail.setQuantity(1);
            navSellOrderDetail.setDiscount(orderGoods.getSellerDiscount().add(orderGoods.getPlatformDiscount()));
            navSellOrderDetail.setAmount(orderGoods.getSalePrice());
//            navSellOrderDetail.setTransactionCost();// 交易费
//            navSellOrderDetail.setOtherAmount(); // 平台其他费
            navSellOrderDetail.setSaleTax(orderGoods.getTaxAmount());
            navSellOrderDetail.setPlatformStatus("1");

            sellOrderDetailList.add(navSellOrderDetail);
        }
        navSellOrder.setProduct(sellOrderDetailList);

        return navSellOrder;
    }

    /**
     * 获取面单
     * @param orderId
     * @param packageId
     * @param shopId
     * @return
     */
    public SysFile getPackageShippingDocument(String orderId, String packageId, Long shopId) {
        ShopInfo shopInfo = shopInfoService.getById(shopId);

        Map<String,String> header = new HashMap<>();
        header.put("x-tts-access-token", shopInfo.getRefreshToken());


        Map<String, Object> query = new TreeMap<>();
        query.put("access_token", shopInfo.getRefreshToken());
        query.put("shop_cipher", shopInfo.getMarketplaceId());
        query.put("document_type", "SHIPPING_LABEL_PICTURE");

//            Map<String,Object> params = new HashMap<>();
//            params.put("document_type","SHIPPING_LABEL_AND_PACKING_SLIP");

        Map<String,Object> currentParamsMap = new HashMap<>();
//        currentParamsMap.put("params",params);
        currentParamsMap.put("query",query);
        currentParamsMap.put("path",packageId);

        Object result = datainterfaceService.executeInterface(null, "EC00530", null, currentParamsMap, header);
        JSONObject body = JSONUtil.parseObj(result);
        //AWAITING_COLLECTION 状态订单才会有面单
        if (body.getInt("code").equals(0)) {
            String docUrl = body.getJSONObject("data").getStr("doc_url");
            SysFile doc = uploadDoc(orderId, packageId, docUrl);
            return doc;
        } else {
            throw new RuntimeException(StrUtil.subPre(body.getStr("message"), 2000));
        }
    }

//    public SysFile getPackageShippingDocument(String orderId, String packageId, Long shopId) {
//        ShopInfo shopInfo = shopInfoService.getById(shopId);
//
//        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode, "TikTok"), false);
//        String rootPath = entityAuthority.getRootPath();
//        String appKey = common.getAuthoritySimpleFactory(entityAuthority, "appKey");
//        String appSecret = common.getAuthoritySimpleFactory(entityAuthority, "appSecret");
//
//
//        HttpHeaders header = new HttpHeaders();
//        header.set("Content-Type", "application/json");
//        header.set("x-tts-access-token", shopInfo.getRefreshToken());
//
//        Long timestamp = System.currentTimeMillis() / 1000;
//
//        Map<String, Object> query = new TreeMap<>();
//        query.put("access_token", shopInfo.getRefreshToken());
//        query.put("app_key", appKey);
//        query.put("shop_cipher", shopInfo.getMarketplaceId());
//        query.put("timestamp", timestamp);
//        query.put("document_type", "SHIPPING_LABEL_PICTURE");
//
////            Map<String,Object> params = new HashMap<>();
////            params.put("document_type","SHIPPING_LABEL_AND_PACKING_SLIP");
//
//        String sign = TiktokUtil.getSign(appSecret, "/fulfillment/202309/packages/" + packageId + "/shipping_documents", query, null);
//        query.put("sign", sign);
//
//        StringBuilder pathParam = new StringBuilder();
//        for (String key : query.keySet()) {
//            pathParam.append("&").append(key).append("=").append(query.get(key));
//        }
//        String url = rootPath + "/fulfillment/202309/packages/" + packageId + "/shipping_documents" + "?" + pathParam.substring(1);
//        Object result = TiktokUtil.getBaseAspect().httpRequest(url, HttpMethod.GET, null, header, Object.class, Constants.Read, StrUtil.EMPTY);
//        JSONObject body = JSONUtil.parseObj(result);
//        //AWAITING_COLLECTION 状态订单才会有面单
//        if (body.getInt("code").equals(0)) {
//            String docUrl = body.getJSONObject("data").getStr("doc_url");
//            SysFile doc = uploadDoc(orderId, packageId, docUrl);
//            return doc;
//        } else {
//            throw new RuntimeException(StrUtil.subPre(body.getStr("message"), 2000));
//        }
//    }

    public SysFile uploadDoc(String orderId, String packageId, String docUrl) {
        if (docUrl != null && !docUrl.isEmpty()) {
            MultipartFile multipartFile = null;
            try {
                multipartFile = onlineAddressTransferFile(orderId, packageId, docUrl);
                if (multipartFile != null) {
                    SysFile file = fileService.upload(multipartFile, null);
                    return file;
                }
            } catch (Exception e) {
                log.error("上传失败：" + docUrl, e);
            }
        }
        return null;
    }

    public MultipartFile onlineAddressTransferFile(String orderId, String packageId, String strUrl) throws IOException {
        InputStream stream = getInputStreamByUrl(strUrl);
        if (!ObjectUtils.isEmpty(stream)) {
            String fileName = StrUtil.concat(true, orderId, "_", packageId, ".png");
            return new MockMultipartFile(fileName, fileName, "image/png", stream);
        } else {
            log.error("获取网络文件失败 > " + strUrl);
        }
        return null;
    }

    public InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(strUrl)) {
                URL url = new URL(strUrl);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20 * 1000);

                final ByteArrayOutputStream output = new ByteArrayOutputStream();
                InputStream inputStream = conn.getInputStream();
                IOUtils.copy(inputStream, output);
                return new ByteArrayInputStream(output.toByteArray());
            }
        } catch (FileNotFoundException e) {
            log.error("FileNotFoundException: " + strUrl);
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("获取面单时失败，未知异常: " + strUrl, e);
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                log.error("获取面单时，连接失败: " + strUrl, e);
            }
        }
        return null;
    }
}
